﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using Microsoft.VisualBasic;
using System.Configuration;

namespace 企业人事管理系统
{
    public partial class UserManageForm : DataListForm
    {
        public static string Title = "用户管理";
        public static string UserSQL = string.Format("select {1},{2},{3},{4} from {0}",
            DataName.userTable, //0
            DataName.userID, //1
            DataName.userName, //2 
            DataName.userLevel, //3
            DataName.userDate); // 4

        public static string configLevel = "HighLevel";
        public static string configPassword = "defaultPassword";

        private int allowLEVEL;  //允许访问等级
        private int maxUserLEVEL; //数据库中的最大用户权限
        private Configuration config; //读写配置文件

        //右键菜单项
        private ToolStripSeparator separator;
        private ToolStripMenuItem setAllowItem;
        private EventHandler setAllowEvent;
        private ToolStripMenuItem setPasswordItem;
        private EventHandler setPasswordEvent;

        //用户信息
        private string userName;
        private int userLevel;

        public UserManageForm(string user):base(Title,UserSQL)
        {
            InitializeComponent();
            this.Text = Title;
            userName = user;

            readLevelRequest();
            addMenuItem();

           // testLevel();
            dataShow.AllowUserToAddRows = false;
        }

      

        //测试用户是否拥有足够的权限
        public Boolean testLevel()
        {
            Boolean test = false;
            //每次判断重新获取用户权限
            readNowLevel();
            string message = "";
            if (userLevel >= allowLEVEL)
            {
                message += "恭喜，您的权限足以管理其他用户。\n";
                test = true;
            }
            else
            {
                message += "遗憾，您并没有管理其他用户的权限。\n";
                test = false;
            }
            message += "您的权限：" + userLevel + "\n"; 
            message += "用户中的最大权限：" + maxUserLEVEL + "\n";
            message += "管理其他用户所需权限：" + allowLEVEL;
            MessageBox.Show(message);

            return test;
        }

        //读取用户当前权限
        public void readNowLevel()
        {
            try
            {
                OledbOP.initConnect(DataName.testConStr);
                string sql = string.Format("select {1}  from {0} where {2} = '{3}'",
                    DataName.userTable,
                    DataName.userLevel,
                    DataName.userName,
                    userName
                    );
                OleDbDataReader re = OledbOP.getReader(sql);
                re.Read();
                userLevel = re.GetInt32(0);
                //MessageBox.Show("最大权限" + maxUserLEVEL);

                re.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        //读取权限要求
        private void readLevelRequest()
        {
            allowLEVEL = 0;
            maxUserLEVEL = 0;
            //读取数据库中的最大用户权限
            try
            {
                OledbOP.initConnect(DataName.testConStr);
                string sql = string.Format("select MAX({1})  from {0}",
                    DataName.userTable,
                    DataName.userLevel);
                OleDbDataReader re = OledbOP.getReader(sql);
                re.Read();
                maxUserLEVEL = re.GetInt32(0);
                //MessageBox.Show("最大权限" + maxUserLEVEL);

                re.Close();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            //读取配置文件中的高级权限级别
            config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string l = config.AppSettings.Settings[configLevel].Value;
            try
            {
                allowLEVEL = Convert.ToInt32(l);
            }
            catch (Exception ex)
            {
                MessageBox.Show("配置文件加载错误:" + ex.Message);
            }
            if(allowLEVEL > maxUserLEVEL)
            {
                allowLEVEL = maxUserLEVEL;
            }
            //MessageBox.Show("允许等级：" + allowLEVEL);
        }

        private void addMenuItem()
        {
            separator = new ToolStripSeparator();
            contextMenuDataShow.Items.Add(separator);

            setAllowItem = new ToolStripMenuItem("更改用户管理最低权限");
            contextMenuDataShow.Items.Add(setAllowItem);
            setAllowEvent = new EventHandler(setAllow);
            setAllowItem.Click += setAllowEvent;

            setPasswordItem = new ToolStripMenuItem("更改新用户默认密码");
            contextMenuDataShow.Items.Add(setPasswordItem);
            setPasswordEvent = new EventHandler(setDefaultPassword);
            setPasswordItem.Click += setPasswordEvent;

            contextMenuDataShow.Items[0].Click -= new EventHandler(添加新行ToolStripMenuItem_Click);
            contextMenuDataShow.Items[0].Click += new EventHandler(addNewRow);
        }

        private void setAllow(object sender, EventArgs e)
        {
            string l = Interaction.InputBox("请输入设置的访问权限", "控制权限修改", allowLEVEL.ToString(), -1, -1);
            try
            {
                allowLEVEL = Convert.ToInt32(l);
                //写入设置的文件
                config.AppSettings.Settings[configLevel].Value = allowLEVEL.ToString();
                config.Save();
                MessageBox.Show("权限写入完成");
            }
            catch(Exception ex)
            {
                MessageBox.Show("权限值设置有误:" + ex.Message);
            }

            //MessageBox.Show(config.AppSettings.Settings["HighLevel"].Value);
        }


        //测试权限后显示
        public void showAfterTest()
        {
            if(testLevel())
            {
                this.Show();
            }
        }

        private void setDefaultPassword(object sender, EventArgs e)
        {
            string pass = config.AppSettings.Settings[configPassword].Value;
            string l = Interaction.InputBox("请输入设置的默认密码，作为添加的新管理员的密码", "默认密码修改",pass , -1, -1);
            try
            {
                if (l.Trim().Length <= 0) return;
                //写入设置的文件
                config.AppSettings.Settings[configPassword].Value = l.Trim();
                config.Save();
                MessageBox.Show("默认密码写入成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("默认密码设置有误:" + ex.Message);
            }
            //MessageBox.Show(config.AppSettings.Settings[configPassword].Value);
        }

        private void addNewRow(object sender, EventArgs e)
        {
            DataRow row = ((DataTable)dataShow.DataSource).NewRow();
            try
            {
               
                row[0] = Interaction.InputBox("请输入新用户的[" + DataName.userID + "]", "新用户信息输入", "", -1, -1);
                row[1] = Interaction.InputBox("请输入新用户的[" + DataName.userName + "]", "新用户信息输入", "", -1, -1);
                row[2] = Convert.ToInt32(Interaction.InputBox("请输入新用户的[" + DataName.userLevel + "]", "新用户信息输入", "", -1, -1));
                row[3] = DateTime.Now;
            }catch(Exception ex)
            {
                MessageBox.Show("新行插入失败："+ex.Message);
                return;
            }
            ((DataTable)dataShow.DataSource).Rows.Add(row);
            addRowIntoData();
        }
      
        private void addRowIntoData()
        {
            
            DataGridViewRow row = dataShow.Rows[dataShow.RowCount - 1];
            string sql = string.Format("insert into {0} values({1},'{2}','{3}',{4},'{5}')",
                DataName.userTable,
                row.Cells[0].Value,
                row.Cells[1].Value,
                config.AppSettings.Settings[configPassword].Value,
                row.Cells[2].Value,
                row.Cells[3].Value
                );
            try
            {
                OledbOP.initConnect(DataName.testConStr);
                if (OledbOP.execute(sql) > 0)
                {
                    MessageBox.Show("新用户注册成功，默认密码为：" + config.AppSettings.Settings[configPassword].Value);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("注册失败：" + ex.Message);
            }
        }


    }
}
